package com.quan.upms.rpc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tk.mybatis.mapper.entity.Condition;

import com.quan.common.core.support.BaseService;
import com.quan.upms.rpc.api.UpmsCompanyService;
import com.quan.upms.rpc.dao.mapper.UpmsCompanyMapper;
import com.quan.upms.rpc.dao.mapper.UpmsDepartmentMapper;
import com.quan.upms.rpc.dao.mapper.UpmsUserCompanyDeptAssignMapper;
import com.quan.upms.rpc.model.UpmsCompany;
import com.quan.upms.rpc.model.UpmsDepartment;
import com.quan.upms.rpc.model.UpmsUserCompanyDeptAssign;

@Service
public class UpmsCompanyServiceImpl extends BaseService<UpmsCompany> implements UpmsCompanyService {
	
	@Autowired
	private UpmsCompanyMapper mapper ;
	
	@Autowired
	private UpmsDepartmentMapper upmsDepartmentMapper;
	
	@Autowired
	private UpmsUserCompanyDeptAssignMapper upmsUserCompanyDeptAssignMapper;
	
	@Override
	public List<UpmsCompany> selectRoot() {
		return this.mapper.selectRoot();
	}
	
	
	@Override
	public int deleteById(Object id) {
		return recursiveDelete(Integer.valueOf(id.toString()));
	}
	
	private int recursiveDelete(Integer id) {
		List<UpmsCompany> loadChildrenNode = this.selectChildren(id) ;
		if(null != loadChildrenNode) {
			for (UpmsCompany company : loadChildrenNode) {
				recursiveDelete(company.getId());
			}
		}
		
		//删除关联该公司的用户关联关系
		Condition condition = new Condition(UpmsUserCompanyDeptAssign.class) ;
		condition.createCriteria().andEqualTo("companyId", id);
		this.upmsUserCompanyDeptAssignMapper.deleteByCondition(condition) ;
		
		//删除该公司下的部门
		Condition ucd = new Condition(UpmsDepartment.class) ;
		ucd.createCriteria().andEqualTo("companyId", id);
		this.upmsDepartmentMapper.deleteByCondition(ucd) ;
		
		return super.deleteById(Integer.valueOf(id.toString())) ;
	}

	@Override
	public List<UpmsCompany> selectChildren(Integer pid) {
		return this.mapper.selectChildren(pid);
	}

	@Override
	public List<UpmsCompany> tree(UpmsCompany entity) {
		List<UpmsCompany> list = new ArrayList<UpmsCompany>() ;
		
		List<UpmsCompany> selectRoot = this.selectRoot() ;
		for (UpmsCompany company : selectRoot) {
			list.add(recursive(company)) ;
		}
		return list;
	}
	
	private UpmsCompany recursive(UpmsCompany company) {
		
		List<UpmsCompany> selectChildren = this.selectChildren(company.getId()) ;
		if(null != selectChildren && !selectChildren.isEmpty()) {
			List<UpmsCompany> children = new ArrayList<UpmsCompany>() ;
			
			for (UpmsCompany child : selectChildren) {
				children.add(recursive(child)) ;
			}
			
			company.setChildren(children);
		}
		return company ;
	}

	@Override
	public void removeCompanyAssignAllUser(Integer companyId) {
		UpmsUserCompanyDeptAssign entity = new UpmsUserCompanyDeptAssign() ;
		entity.setCompanyId(companyId);
		this.upmsUserCompanyDeptAssignMapper.delete(entity) ;		
	}
	
}
